#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* reverseWords(char* s) {
    #define swap(c1, c2) do {char __c = c1; c1 = c2; c2 = __c;} while(0)
    int w_s = 0, w_e = 0;
    int idx = 0;
    char *ans = (char*)malloc(1e5);
    memset(ans, '\0', 1e5);
    int ans_idx = 0;

    int find_start = *s == ' ' ? 1 : 0;
    while (*(s+idx)) {
        while(*(s+idx) && find_start && *(s+idx) == ' ') 
            idx++;

        if (find_start) {
            w_s = idx;
            find_start = 0;
            idx++;
        } 
        
        while(*(s+idx) && !find_start && *(s+idx) != ' ') 
            idx++;

        if (!find_start){
            w_e = idx;
            /*
            for (int i = w_s; i < w_e; i++)
                printf("%c", s[i]);
            printf("\n");
            */
            //for (int i = w_s, j = w_e-1; i < j; i++, j--)
            //    swap(*(s+i), *(s+j));
            for (int i = w_e - 1; i >= w_s; i--) {
                *(ans + ans_idx++) = *(s+i);
            }
            *(ans + ans_idx++) = ' ';
            find_start = 1;
            idx++;
        }
    }
    *(ans + ans_idx) = '\0';
    return ans;
}

int main(void)
{
    printf("#151. 反转字符串中的单词\n\n");
    printf("leetcode error occur. to check it later!\n\n");
    char s[] = " my  name is zhang te";
    printf("%s\n", s);
    char *ans = reverseWords(s);
    printf("%s\n", s);
    printf("%s\n", ans);

    return 0;
}